import 'package:m2_flutter/service/CacheService.dart';

class SqlManager {
  static getById(int id) async {
    var originList = await CacheService.getList("data");
    var list = [];
    if (originList != null && originList.isNotEmpty) {
      list = originList;
    }
    if (list.isEmpty) return [];
    var res = list.where((element) => element['id'] == "$id");
    return res.first;
  }

  static add(
      {required String money,
      required String reason,
      required DateTime date}) async {
    var res = await CacheService.getList("data");
    var v = [];
    if (res != null && res.isNotEmpty) {
      v = res;
    }

    v.add({
      "id": "${DateTime.now().millisecondsSinceEpoch}",
      "money": money,
      "reason": reason,
      "year": "${date.year}",
      "month": "${date.month}",
      "day": "${date.day}",
    });
    await CacheService.putList("data", v);
  }

  static update(
      {required DateTime date,
      required String money,
      required String reason,
      required String id}) async {
    var originList = await CacheService.getList("data");
    var list = [];
    if (originList != null && originList.isNotEmpty) {
      list = originList;
    }
    list.removeWhere((element) => "${element['id']}" == id);
    list.add({
      "id": id,
      "money": money,
      "reason": reason,
      "year": "${date.year}",
      "month": "${date.month}",
      "day": "${date.day}",
    });
    await CacheService.putList("data", list);
  }

  static Future<List<Map>> getByDate(DateTime date_now) async {
    var originList = await CacheService.getList("data");
    var list = [];
    if (originList != null && originList.isNotEmpty) {
      list = originList;
    }
    if (list.isEmpty) return [];
    var res = list.where((element) =>
        element['year'] == "${date_now.year}" &&
        element['month'] == "${date_now.month}");
    List<Map> resList = [];
    for (var element in res) {
      resList.add(element);
    }
    return resList;
  }

  static deleteById(String s) async {
    var originList = await CacheService.getList("data");
    var list = [];
    if (originList != null && originList.isNotEmpty) {
      list = originList;
    }
    List<Map> resList = [];
    for (var element in list) {
      if ("${element['id']}" != s) {
        resList.add(element);
      }
    }
    await CacheService.putList("data", resList);
  }
}
